package sources.services;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

public class ConversorService
{
    Charset charset = Charset.forName( "ISO-8859-1" );
    CharsetDecoder decoder = charset.newDecoder();
    CharsetEncoder encoder = charset.newEncoder();

    public String UnpacketString(
        CharBuffer cb )
    {
        String sReturn = "";

        if( cb.hasArray() ) {
            int limit = cb.length();
            for( int i = 0; i < limit; i++ ) {
                sReturn += String.valueOf( cb.charAt( i ) );
            }
        }

        return sReturn;
    }

    public String buildNewString(
        ByteBuffer buffer,
        int counter,
        String name )
    {
        CharBuffer out;
        try {
            out = decoder.decode( buffer );
            return new String( String.valueOf( out.charAt( 0 ) ) + String.valueOf( counter ) + name );
        } catch( CharacterCodingException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "invalid";
    }

    public ByteBuffer preparePacket(
        String string )
    {
        try {
            return encoder.encode( CharBuffer.wrap( string ) );
        } catch( CharacterCodingException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}